<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="formData" labelWidth="28%">
		  <uni-forms-item label="登录名" name="userName" required>
		    <uni-easyinput v-model="formData.userName" placeholder="请输入登录名,规则:用户名称的首字母缩写;若有重复,请自定义规则" maxlength="20"/>
		  </uni-forms-item>
		  <uni-forms-item v-if="!this.formData.userId" label="密码" name="password" required>
		    <uni-easyinput v-model="formData.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
		  </uni-forms-item>
		  <uni-forms-item label="姓名" name="name" required>
			<uni-easyinput v-model="formData.name" placeholder="请输入姓名"></uni-easyinput>
		  </uni-forms-item>
		  <uni-forms-item label="归属部门" name="cateId" required>
		   <uni-easyinput @click.native="showTree2()" v-model="deptName" placeholder="请选择部门" ></uni-easyinput>
			 <gqTree 
			  ref="gqTreeDept"
			  :range="deptOptions" 
			  idKey="id"
			  nameKey="label"
			  childKey="children"
			  pidKey="pid"
			  :showSearch="false"
			  :cascade="true"
			  :multiple="false"
			  @confirm="comfirmDept"
			 ></gqTree>
		  </uni-forms-item>
		  <uni-forms-item label="角色" name="cateId" required>
		  <uni-easyinput @click.native="showTree()" v-model="rolesName" placeholder="请选择角色" ></uni-easyinput>
			 <gqTree 
			  ref="gqTreeRole"
			  :range="roleOptions" 
			  idKey="roleId"
			  nameKey="roleName"
			  :showSearch="false"
			  :cascade="true"
			  @confirm="comfirmRole"
			 ></gqTree>
		  </uni-forms-item>
		  <uni-forms-item label="排序" name="sort" required>
			<uni-easyinput type="number" v-model="formData.sort" placeholder="请输入排序"></uni-easyinput>
		  </uni-forms-item>
		  <uni-forms-item label="状态" name="status" required>
			<uni-data-select
			  v-model="formData.status"
			  :localdata="sys_show_hide"
			  :clear="false"
			></uni-data-select>
		  </uni-forms-item>
      </uni-forms>
      <button class="button-blue" @click="save()">保存</button>
    </view>
  </view>
</template>

<script>
  import { checkPermi } from "@/utils/permission";
  import { memberApi } from '@/api/module';
  import { getDictValue } from '@/api/system/dict/data';
  import { getUser,deptTreeSelect } from '@/api/system/user';
  import gqTree from '@/components/gq-tree/gq-tree';

  export default {
    components:{
	  gqTree,
    },
    data() {
      return {
	   //表单
	   formData: {
		   name:"",
		   positon:"",
		   status:"0",
		   sort:"",
		   id:null,
	   },
		
		//表单规则判断
        rules: {
		  name: {
		    rules: [{
			  required: true,
			  errorMessage: '请输入姓名'
		    }]
		  },
          sort: {
            rules: [{
              required: true,
              errorMessage: '请输入排序'
            }]
          },
		  status: {
			  rules: [{
			    required: true,
			    errorMessage: '请选择状态'
			  }]
		  }
        },
		itemStyle: "background-color: #8cd7fb;border-radius: 0px 19px 0px 0px",
		sys_show_hide:[],
		deptOptions:[],
		roleOptions:[],
		deptName:"",
		rolesName:"",
      }
    },
    async onLoad(option) {
		await this.getDeptTree();
		await this.getRoles();
		if(option.formData){
			let covertData = JSON.parse(option.formData)
			this.formData = {...covertData};
			this.checkUser();
		}
		
		getDictValue("sys_show_hide", this);
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
	  //权限
	  checkPermi,
	  //部门选择确认
	  comfirmDept(list){
	      const idKeysResult = list.map((x)=>{
		    return x.id.toString();
		  });
		  this.formData.deptId = idKeysResult.toString();
		  const options = JSON.parse(JSON.stringify(this.deptOptions))
		  const newOptions = this.deepCheckValue("DEPTS",options,idKeysResult,'id','children')
		  this.deptOptions = [...newOptions];
	  },
	  //角色选择确认
	  comfirmRole(list){
	      const idKeysResult = list.map((x)=>{
			return x.id.toString();
		  });
		  this.formData.roleIds = idKeysResult;
		  const options = JSON.parse(JSON.stringify(this.roleOptions))
		  const newOptions = this.deepCheckValue("ROLES",options,idKeysResult.toString(),'roleId')
		  this.roleOptions = [...newOptions];
	  },
	  showTree() {		  
		  this.$refs.gqTreeRole._show();
	  },
	  showTree2() {
	  				  
		  //打开选择器
		  this.$refs.gqTreeDept._show();
		  //关闭选择器
		  //this.$refs.gqTree._hide();
	  },
	  //获取角色列表
	  async getRoles(){
		  await getUser().then(response => {
			this.roleOptions = response.roles;
		  })
	  },
	  //获取部门树
	  async getDeptTree() {
	    await deptTreeSelect().then(response => {
	      this.deptOptions = this.filerDeptList(response.data);
	    });
	  },
	  
	  filerDeptList(treeData) {
	    return treeData.map((item) => {
		  let pid = item.id
	      if(item.children){
			  for(let v of item.children){
				 v.pid = pid;
			  }
	      }
	      return item
	    })
	  },
	  
	  deepCheckValue(args,options,values,idKey,childKey){
	  		return options.map((i)=>{
	  		  if(values.indexOf(i[idKey].toString()) > -1){ 
	  			i['isGqAddChecked'] = true;
				if(args == "DEPTS"){
					if(this.deptName.indexOf(i.name) == -1){
						this.deptName = i.label;
					}
				}else if(args == "ROLES"){
					if(this.rolesName.indexOf(i.name) == -1){
						this.rolesName = this.rolesName + "/" + i.roleName;
					}
				}
	  			
	  		  }else{
	  			i['isGqAddChecked'] = false
	  		  }
			  if(childKey){
				  if(i[childKey] && i[childKey].length>0){
					this.deepCheckValue(args,i[childKey],values,idKey,childKey)
				  }
			  }
	  		  return i
	  		})
	  },
	  
	  //检查用户
	  checkUser(){
		  let userId = this.formData.userId
		  getUser(userId).then(response => {
			  this.roleOptions = response.roles;
			  if(response.data.dept){
				  if(response.data.dept.deptId){
					  let deptId = response.data.dept.deptId
					  const options = JSON.parse(JSON.stringify(this.deptOptions))
					  let newOptions = this.deepCheckValue("DEPTS",options,deptId.toString(),'id','children');
					  this.deptOptions = [...newOptions];
				  }
			  }
			  this.formData.deptId = response.data.dept.deptId;
			  if(response.roleIds){
				  let roleOptions = JSON.parse(JSON.stringify(this.roleOptions))
				  let newRoleOptions = this.deepCheckValue("ROLES",roleOptions,response.roleIds.toString(),'roleId');
				  this.roleOptions = [...newRoleOptions];
			  }
			  this.$set(this.formData, "userName", response.data.userName);
			  this.$set(this.formData, "roleIds", response.roleIds);
			  this.$set(this.formData, "password", "");
		  });  
	  },
	  save(){
		  this.$refs.form.validate().then(res=>{
			  let that = this;
			  uni.showLoading()
			  this.formData.createTime = null;
			  this.formData.updateTime = null;
			  memberApi.saveMember(this.formData).then(data => {
				  uni.hideLoading();
				  this.$modal.msgSuccess('操作成功');
				  setTimeout(function(){
					  that.$tab.navigateTo('/pages/module/member/list');
				  },800)
				  
			  })
		  })
	  },
	  
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .example {
    padding: 15px;
    background-color: #fff;
  }

  .segmented-control {
    margin-bottom: 15px;
  }

  .button-group {
    margin-top: 15px;
    display: flex;
    justify-content: space-around;
  }

  .form-item {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .button {
    display: flex;
    align-items: center;
    height: 35px;
    line-height: 35px;
    margin-left: 10px;
  }
</style>
